import ROBOT_AVATAR from '@/assets/image/avatar_robo.png';
import {
  brain_space_feedback_items,
  brain_space_good_sentence,
  delete_brain_space_good_sentence,
} from '@/services/ant-design-pro/brainSpace';
import { LeftOutlined } from '@ant-design/icons';
import { connect } from '@umijs/max';
import type { TabsProps } from 'antd';
import { Empty, message, Modal, Pagination, Select, Tabs } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import LongDocItem from '../LongDocItem';
import './index.less';
const dayjs = require('dayjs');

const GoodWordsAndSentences: React.FC<any> = forwardRef((props: any, ref) => {
  const { title } = props;
  const tagKey = useRef(''); // tag的key
  //分页默认值，
  const [pageOption, setPageOption] = useState({
    page: 1, //当前页为1
    per_page: 10, //一页10行
  });
  const [loaded, setLoaded] = useState(false); // 加载完成
  const [commentLoaded, setCommentLoaded] = useState(false); // 点彩加载完成
  const [defaultActiveKey, setDefaultActiveKey] = useState('MY_FEEDBACK'); // 默认激活的tab
  const [totalCount, setTotalCount] = useState(0); // 文章总数
  const [totalCommentCount, setTotalCommentCount] = useState(0); // 点彩总数
  const [pageCommentIndex, setPageCommentIndex] = useState(1); // 点彩索引
  const [dataList, setDataList] = useState<any[]>([]); // 文档列表
  const [typeOptions, setTypeOptions] = useState<any[]>([]); // 类型列表
  const [commentList, setCommentList] = useState<any[]>([]); // 点彩列表
  const [commentShow, setCommentShow] = useState(false); // 点踩弹出框
  const [commentDetail, setCommentDetail] = useState(false); // 点踩详情
  const articleElement = useRef<any>(null);
  const items: TabsProps['items'] = [
    // {
    //   key: 'DEPARTMENT',
    //   label: '行政局',
    // },
    // {
    //   key: 'COMMON',
    //   label: '公共',
    // },
    {
      key: 'MY_FEEDBACK',
      label: '我反馈的',
    },
    {
      key: 'MY_TRAIN',
      label: '我训练的',
    },
  ];

  useImperativeHandle(ref, () => ({
    reloadData: () => {
      setPageOption({
        page: 1, //当前页为1
        per_page: 10, //一页10行
      });

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      loadMoreData(1, 10, defaultActiveKey);
    },
  }));

  // 时间格式
  const formatAtTime = (timestamp: any) => {
    return dayjs(timestamp).format('YYYY.MM.DD HH:mm:ss');
  };

  // 类型
  const loadCognitionTypes = async () => {
    const data: any = [{ value: '', label: '全部类型' }];
    props.spaceModel.cognitionTypes.forEach((v: any) => {
      if (v.name === 'good_sentence' && v.second_class_list && v.second_class_list.length) {
        v.second_class_list.forEach((c_v: any) => {
          const obj: any = {
            value: c_v,
            label: c_v,
          };
          data.push(obj);
        });
      }
    });
    setTypeOptions(data);
  };
  // 加载数据
  const loadMoreData = async (page: number, per_page: number, scope_class: string) => {
    const params: any = { page, per_page, scope_class };
    if (tagKey.current) {
      params.tag = tagKey.current;
    }
    const res = await brain_space_good_sentence(params);
    if (res.code === 0) {
      if (res.data.data && res.data.data.length) {
        const { total_count, data } = res.data;
        data.forEach((v: any) => {
          v.release_time = v.updated_at ? formatAtTime(v.updated_at) : '-';
          v.tags = v.tags ? v.tags : '-';
          v.deleteShow = true;
          v.showTag = true;
        });
        setTotalCount(total_count);
        setDataList(data);
      } else {
        setDataList([]);
      }
      setLoaded(true);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  // 点赞列表
  const loadFeedbackItemsPraise = async (page: number, per_page: number) => {
    const params: any = { page, per_page, feedback_type: 1 };
    const res = await brain_space_feedback_items(params);
    if (res.code === 0) {
      if (res.data.data && res.data.data.length) {
        const { total_count, data } = res.data;
        data.forEach((v: any, i: number) => {
          v.id = v.id ? v.id : i;
          v.second_class = v.feedback_type === 1 ? '点赞' : v.feedback_type === 2 ? '点踩' : '-';
          v.color = v.feedback_type === 1 ? '#56BA9B' : v.feedback_type === 2 ? '#E36E6E' : '';
          v.background = v.feedback_type === 1 ? '#D1F7EB' : v.feedback_type === 2 ? '#FFE1DE' : '';
          v.main_body = v.target_content ? v.target_content : '-';
          v.release_time = v.created_at ? formatAtTime(v.created_at) : '-';
          v.updated_at = v.created_at ? v.created_at : '-';
          v.deleteShow = false;
          v.showTag = true;
        });
        setTotalCount(total_count);
        setDataList(data);
      } else {
        setDataList([]);
      }
      setLoaded(true);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  // 点踩列表
  const loadFeedbackItemsList = async (page: number, per_page: number) => {
    const params: any = { page, per_page, feedback_type: 2 };
    const res = await brain_space_feedback_items(params);
    if (res.code === 0) {
      if (res.data.data && res.data.data.length) {
        const { total_count, data } = res.data;
        data.forEach((v: any, i: number) => {
          v.id = v.id ? v.id : i;
          v.second_class = v.feedback_type === 1 ? '点赞' : v.feedback_type === 2 ? '点踩' : '-';
          v.color = v.feedback_type === 1 ? '#56BA9B' : v.feedback_type === 2 ? '#E36E6E' : '';
          v.background = v.feedback_type === 1 ? '#D1F7EB' : v.feedback_type === 2 ? '#FFE1DE' : '';
          v.main_body = v.target_content ? v.target_content : '-';
          v.release_time = v.created_at ? formatAtTime(v.created_at) : '-';
          v.updated_at = v.created_at ? v.created_at : '-';
          v.deleteShow = false;
          v.showTag = true;
        });
        setTotalCommentCount(total_count);
        setCommentList(data);
      } else {
        setTotalCommentCount(0);
        setCommentList([]);
      }
      setCommentLoaded(true);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };

  // 删除
  const handleDelete = async (id: string) => {
    const res = await delete_brain_space_good_sentence(id);
    if (res.code === 0) {
      // 删除成功
      message.open({
        type: 'success',
        content: '删除成功',
      });
      loadMoreData(1, 10, defaultActiveKey);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };

  // 切换tab
  const handleTabChange = (e: any) => {
    setDefaultActiveKey(e);
    setPageOption({
      page: 1,
      per_page: 10,
    });
    setTotalCount(0);
    if (e === 'MY_FEEDBACK') {
      loadFeedbackItemsPraise(1, 10);
    } else {
      loadMoreData(1, 10, e);
    }
    props.dispatch({
      type: 'spaceBot/updateStateAsync',
      payload: {
        goodSentenceTab: e,
      },
    });
  };

  // 类型切换
  const handleTypeChange = (value: string) => {
    tagKey.current = value;
    setPageOption({
      page: 1,
      per_page: 10,
    });
    setTotalCount(0);
    loadMoreData(1, 10, defaultActiveKey);
  };

  // 页数切换
  const paginationChange = async (current: number, size: number) => {
    //前面用到useState
    setPageOption({
      page: current, //当前所在页面
      per_page: size, //一页有几行
    });
    if (defaultActiveKey === 'MY_FEEDBACK') {
      loadFeedbackItemsPraise(current, size);
    } else {
      loadMoreData(current, size, defaultActiveKey);
    }
  };

  // 点踩页数切换
  const paginationCommentChange = async (current: number, size: number) => {
    setPageCommentIndex(current);
    loadFeedbackItemsList(current, size);
  };

  const goBack = () => {
    setCommentDetail(false);
  };

  //page变动时触发请求
  useEffect(() => {
    loadCognitionTypes();
    if (defaultActiveKey === 'MY_FEEDBACK') {
      loadFeedbackItemsPraise(pageOption.page, pageOption.per_page);
    } else {
      loadMoreData(pageOption.page, pageOption.per_page, defaultActiveKey);
    }
  }, []);

  //关闭点彩
  const commentShowCancel = () => {
    setCommentShow(false);
  };
  //显示点彩
  const handleComment = (e: any) => {
    e.stopPropagation(); //阻止冒泡
    setCommentShow(true);
    loadFeedbackItemsList(1, 10);
  };
  //显示点彩详情
  const handleCommentDetail = (event: any, item: any) => {
    event.stopPropagation(); //阻止冒泡
    //将\n替换成p标签包裹文字
    const dt = item.main_body
      .split('\n')
      .map((paragraph: any) => `<p>${paragraph}</p>`)
      .join('');
    setCommentDetail(true);
    articleElement.current = React.createElement('div', {
      dangerouslySetInnerHTML: { __html: dt },
    });
  };

  return (
    <div className="GoodWordsAndSentences p-r">
      <div className="page-container">
        <div className="statefulComponent">
          <div className="f-s-20 doc-title">{title ? title : '好词好句空间'}</div>
          <div className="p-r">
            <div className="">
              <Tabs defaultActiveKey="1" items={items} onChange={(e) => handleTabChange(e)} />
            </div>
            <div className="p-a select-type m-t-5">
              {(defaultActiveKey === 'DEPARTMENT' || defaultActiveKey === 'COMMON') && (
                <Select
                  defaultValue={tagKey.current}
                  style={{ width: 120 }}
                  onChange={handleTypeChange}
                  options={typeOptions}
                />
              )}
              {defaultActiveKey === 'MY_FEEDBACK' && (
                <div className="flex-center">
                  <img
                    className="problem-avatar m-r-10"
                    src={ROBOT_AVATAR}
                    alt=""
                    height={30}
                    width={30}
                  />
                  <div className="flex-center tips-box">
                    <div>点踩内容小麦默默记下了，会默默改正的。</div>
                    <div className="ele-tips" onClick={(event) => handleComment(event)}>
                      查看点踩内容
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
          {dataList.length === 0 && loaded && (
            <Empty className="empty" image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
          {dataList.length > 0 && (
            <div className="top-doc-box other-doc">
              <div className="GWASBox">
                {dataList.map((item: any) => {
                  return (
                    <LongDocItem
                      key={item.id}
                      item={item}
                      type="otherDoc"
                      titleType="tag"
                      deleteShow={defaultActiveKey === 'MY_TRAIN' ? true : false}
                      deleteItem={handleDelete}
                    />
                  );
                })}
              </div>
            </div>
          )}
          {/* 分页 */}
          {dataList.length > 0 && (
            <div className="flex-jcon-end m-t-10">
              <Pagination
                current={pageOption.page}
                defaultCurrent={1}
                pageSize={pageOption.per_page}
                total={totalCount}
                showSizeChanger={false}
                onChange={paginationChange}
              />
            </div>
          )}
          {/* 点踩弹窗 */}
          <Modal
            centered
            className="not-good-modal"
            title={'点踩内容'}
            open={commentShow}
            onCancel={commentShowCancel}
            width={1220}
            footer={
              !commentDetail && [
                <div className="flex-jcon-end" key="key">
                  <Pagination
                    defaultCurrent={1}
                    current={pageCommentIndex}
                    total={totalCommentCount}
                    showSizeChanger={false}
                    onChange={paginationCommentChange}
                  />
                </div>,
              ]
            }
          >
            <div>
              {commentDetail && (
                <div>
                  <div onClick={() => goBack()} className="flex c-p">
                    <LeftOutlined style={{ fontSize: '14px', cursor: 'pointer' }} />
                    <div className="m-l-5">返回</div>
                  </div>
                  <div className="m-t-10">
                    <div>{articleElement.current}</div>
                  </div>
                </div>
              )}
              {!commentDetail && (
                <div>
                  {commentList.length === 0 && commentLoaded && <Empty />}
                  {commentList.length > 0 && (
                    <div className="top-doc-box other-doc">
                      <div className="GWASBox">
                        {commentList.map((item: any) => {
                          return (
                            <LongDocItem
                              key={item.id}
                              item={item}
                              boxWidth="530px"
                              showDemo={handleCommentDetail}
                              type="otherDoc"
                              titleType="tag"
                              deleteShow={false}
                            />
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </Modal>
        </div>
      </div>
    </div>
  );
});
export default connect(({ spaceModel }) => ({ spaceModel }), null, null, { forwardRef: true })(
  GoodWordsAndSentences,
);
